package com.bijiawang.user.service;

import com.bijiawang.user.domin.Favorites;
import com.bijiawang.user.domin.Nfavorites;
import com.bijiawang.user.repository.FavoritesRepository;
import com.bijiawang.user.repository.NfavoritesRepository;
import flexjson.JSONSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class FavoritesService {
    @Autowired
    private FavoritesRepository favoritesRepository;
    @Autowired
    private NfavoritesRepository nfavoritesRepository;
    private static int goodsId = 0;
    //用户名要通过安全模块中保存的值来获取
//    private static String userName = "李四";
    public void saveToFavorites(String userName,String goodsName,String goodsUrl,Double goodsPrice,String shopName){
        Favorites favorites = new Favorites();
        String id = "";
        UUID uuid = UUID.randomUUID();
        id = uuid.toString();
        //去掉随机ID的短横线
        id = id.replace("-", "");
        //将随机ID换成数字
        goodsId = id.hashCode();
        //goodsId有可能为负，取绝对值
        goodsId = goodsId < 0 ? -goodsId : goodsId;
        favorites.setGoodsId(goodsId);

        favorites.setUserName(userName);
        favorites.setGoodsName(goodsName);
        favorites.setGoodsPrice(goodsPrice);
        favorites.setGoodsUrl(goodsUrl);
        favorites.setShopName(shopName);

        //保存到表一中
        favoritesRepository.saveAndFlush(favorites);
    }

    public void saveToNfavorites(String username,String goodsName,String goodsUrl,Double goodsPrice,String shopName){
        Nfavorites nfavorites = new Nfavorites();
        nfavorites.setGoodsId(goodsId);
        //用户名要通过安全模块中保存的值来获取
        nfavorites.setUserName(username);
        //正确的用法
        nfavorites.setGoodsName(goodsName);
        nfavorites.setGoodsPrice(goodsPrice);
        nfavorites.setGoodsUrl(goodsUrl);
        nfavorites.setShopName(shopName);

        //保存到表二中
        nfavoritesRepository.saveAndFlush(nfavorites);
    }

    public List<Favorites> getFavorites(String userName){
        return favoritesRepository.findAllByUserName(userName);
    }
    public List<Nfavorites> getAllByOne(int goodsId){
        return nfavoritesRepository.findAllByGoodsIdOrderByOrderNumberAsc(goodsId);
    }
//    public void updateUsername(String oldUsername,String newUsername){
//        favoritesRepository.updateUsername(oldUsername,newUsername);
//        nfavoritesRepository.updateUsername(oldUsername,newUsername);
//    }

//    public String toJson(List<Nfavorites> favorites){
//        JSONSerializer serializer = new JSONSerializer();
//        serializer.exclude("class","orderNumber","goodsId","userName","goodsName","goodsUrl","shopName");
//        return serializer.serialize(favorites);
//    }

    public void deleteFavorites(int goodsId){
        favoritesRepository.deleteByGoodsId(goodsId);
        nfavoritesRepository.deleteByGoodsId(goodsId);
    }

}
